<?php
/**
 * Created by PhpStorm.
 * User: 陈鸿
 * Date: 2016/5/19
 * Time: 15:12
 */

namespace wxOpen;
use wxOpen\Common;
use wxOpen\Error;
use wxOpen\Curl;

class WeiXin extends Error
{
    /**
     * 用户授权登陆 在回调里获得 code 和 state
     *
     * @param null $appid
     * @param null $redirect_uri
     */
    public static function getCode($appid=null,$redirect_uri=null)
    {
        $state        = md5(uniqid('',true) . rand(0,99999));
        $appid        = $appid ? $appid : Common::getFiled('app','appId');
        $redirect_uri = $redirect_uri ? $redirect_uri : Common::getFiled('redirect_uri');
        $param = [
            'appid'         => $appid,
            'redirect_uri'  => $redirect_uri,
            'response_type' => 'code',
            'scope'         => 'snsapi_login',
            'state'         => $state
        ];
        // @todo 这里需要将 $state 存入到缓存里，回调的时候验证 csrf 攻击
        file_put_contents('state_code.log',$state);
        $url = Common::getFiled('codeUrl') . '?' . http_build_query($param);
        header('Location:' . $url);
    }

    /**
     * 能过 code 换取 access_token
     *
     * @param null $appid
     * @param null $secret
     * @desc access_token有效期（目前为2个小时）
     * @return array|bool
     */
    public static function getAccessToken($appid=null,$secret=null)
    {
        $code  = $_GET['code'];
        $state = $_GET['state'];
        $cacheState = file_get_contents('state_code.log');

        if ( $state != $cacheState )
        {
            //return self::get('1');
        }

        $param = [
            'appid'      => $appid  ? $appid  : Common::getFiled('app','appId'),
            'secret'     => $secret ? $secret : Common::getFiled('app','AppSecret'),
            'code'       => $code,
            'grant_type' => 'authorization_code'
        ];

        $accessTokenUrl = Common::getFiled('accessTokenUrl') . '?' . http_build_query($param);

        $json = Curl::get($accessTokenUrl);

        return self::get(json_decode($json,true));
    }

    /**
     * 刷新access_token有效期
     *
     * @param $refresh_token
     * @param null $appid
     * @desc refresh_token拥有较长的有效期（30天）
     * @return array|bool
     */
    public static function refreshToken($refresh_token,$appid=null)
    {
        $param = [
            'grant_type' => 'refresh_token',
            'appid'      => $appid  ? $appid  : Common::getFiled('app','appId'),
            'refresh_token' => $refresh_token
        ];

        $refreshTokenUrl = Common::getFiled('refreshTokenUrl') . '?' . http_build_query($param);

        $json = Curl::get($refreshTokenUrl);

        return self::get(json_decode($json,true));
    }
}